import React, { useEffect, useRef, useState } from "react";
import "./ChatForm.css";
import { sendText } from "@/api/chatAPi";
import { getLrc, getMusicUrl } from "@/api/songAPi";
import songStore from "@/store/songStore";
import { observer } from "mobx-react-lite";

const ChatForm: React.FC<{ setToBottom: Function }> = (props) => {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [textValue, setTextValue] = useState<string>("");
  const [lrcArr, setLrcArr] = useState<any>("");
  const [lrc, setLrc] = useState<string>("");
  const [url, setUrl] = useState<string>("");
  const changeText = (e: React.ChangeEvent<HTMLTextAreaElement>): void => {
    if (e.target) {
      setTextValue(e.target.value);
    }
  };

  const sendMessage = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (event.key === "Enter" && textValue !== "") {
      sendText({
        room_id: Number(localStorage.getItem("room_id")),
        message: textValue,
      });
      setTextValue("");
      props.setToBottom(true);
      event.preventDefault();
    }
  };
  const { songInfo } = songStore;
  useEffect(() => {
    if (songInfo?.song) {
      //获取歌曲url
      console.log(songInfo);
      getMusicUrl(songInfo.song.song.rid).then((res) => {
        setUrl(res.data.url);
      });
      //获取歌词
      getLrc(songInfo.song.song.rid).then((res) => {
        const temp: Record<string, any> = {};
        res.data.lrclist.forEach((item: any) => {
          temp[Math.floor(item.time).toString()] = item;
        });
        setLrcArr(temp);
      });
    }
  }, [songInfo]);
  //是否能播放
  const canPlay = () => {
    audioRef.current?.play();
  };
  //更新歌词
  const audioTimeUpdate = (
    e: React.SyntheticEvent<HTMLAudioElement, Event>
  ) => {
    const audio = e.currentTarget;
    if (audio.duration > 0 && !Number.isNaN(audio.duration)) {
      const temp = lrcArr[Math.floor(audio.currentTime)];
      if (temp) {
        setLrc(temp.lineLyric);
      }
    }
  };
  //歌曲播放结束触发
  const audioEnd = () => {
    setLrc("");
  };

  const audioLoaded = (e: React.SyntheticEvent<HTMLAudioElement, Event>) => {
    if (e.currentTarget) {
      const temp = songInfo.sysTime - songInfo.song.time;
      console.log(songInfo.sysTime, temp);

      if (temp > 0) {
        e.currentTarget.currentTime = temp;
      }
    }
  };
  return (
    <div className={"chat-form"}>
      {/*ChatToolBar*/}
      <div className={"tool"}>
        <div className={"tool-left"}>
          <div className={"tool-item"}>表情</div>
        </div>
        <div className={"tool-right"}>
          <div className={"tool-time"}></div>
        </div>
      </div>
      {/*ChatInput*/}
      <div className={"chat-input"}>
        <textarea
          value={textValue}
          onChange={(e) => changeText(e)}
          onKeyDown={(event) => {
            sendMessage(event);
          }}
        />
        <div className={"lrc"}>{lrc}</div>
        <audio
          src={url}
          ref={audioRef}
          onEnded={audioEnd}
          onLoadedData={audioLoaded}
          onTimeUpdate={(e) => audioTimeUpdate(e)}
          onCanPlay={canPlay}
        ></audio>
      </div>
    </div>
  );
};

export default observer(ChatForm);
